
define(["jquery"],function($){
	$(function(){
		
		
		var loopStyle = {
			base : function(node,style,pre,moz){
				var c = $(node).children("[fill='true']");
				for(var i = 0; i<c.length; i++){
					var nodeName = c[i].nodeName.toLowerCase(),$ci = $(c[i]),cic = $ci.children();
					nodeName = nodeName == "img" ? "image" : nodeName;
					if(cic.length>0){
						var prev = pre ? pre+nodeName+"-" : nodeName+"-";
						this.base(c[i],style,prev);
					}else{
						
						if(pre){
							style.push(pre+nodeName+":"+$ci.html()+";");
						}else{
							style.push(nodeName+":"+$ci.html()+";");
						}
					}
					
				}
			},

			forged : function(node,style,name,pre,moz){
				var c = $(node).children("[fill='true']");
				for(var i = 0; i<c.length; i++){
					var nodeName = c[i].nodeName.toLowerCase(),cic = $(c[i]).children(),
					eleName = $("[data-ctrlId='"+name+"']");

					style.push("[data-ctrlId='"+name+"']:"+nodeName+"{");
					this.base(c[i],style);
					style.push("}");
				}
			},

			keyframes : function(node,style,pre,moz){

			}
		}



		function LoadXML(path,callBack){
			$.ajax({
				type : 'get',
				url : path,
				dataType:"xml",
				success:function(data){
					callBack ? callBack(data) : (function(){
						console.error("NOT callBack");
					}(data));
				}
			})
		}
		
		
		var ctrlKey = [],imgListBOX = '<div id="UEditor_IMGBOX"> <div class="UEditor_top"> <div class="UEditor_title">IMGLIST</div> <div class="UEditor_close">X</div> </div> <div class="UEditor_main"> <div class="UEditor_main_top"> <div class="UEditor_upload"> <input type="file" class="UEditor_upload_file" multiple> <button class="UEditor_upload_button">uploadImg</button> </div> </div> <div class="UEditor_left"></div> <div class="UEditor_right"> <ul class="UEditor_IMGList"> <li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li><li class="UEditor_IMGItem"> <div class="UEditor_IMGItem_box"> <div class="UEditoe_img_title">imgtitle</div> </div> </li> </ul> </div> </div> <div class="UEditor_bottom"></div> </div>'; 
		window.UEditor = function(config){
			var ctrlList ={};
			LoadXML("UEditor/../xml/style.xml",function(xml){

				var $xml =$(xml), 
					ctrlXmlTemplate = $xml.find("styleList ctrl").clone(true),
					baseHTML = ctrlXmlTemplate.find("base").html(),
					ctrlXML,
					ctrlActionXML, 
					$actionXML = $xml.find("scriptList") ,
				    MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver, 
				    // 创建观察者对象  
				    observerStyle = createOberverObj(function(){parseStyleXML(ctrlXML);}),
				    obsetverScript = createOberverObj(function(){
				    	parseScriptXML(ctrlActionXML);

				    });  
				  
				// 配置观察选项:   
				var observerConfig = { attributes: false, childList: true, characterData: true ,attributeOldValue:false,subtree : true,characterDataOldValue:true};
				observerStyle.observe($xml.find("styleList")[0], observerConfig); 
				obsetverScript.observe($xml.find("scriptList")[0],observerConfig);

				ctrlXmlTemplate.find("forged").find("hover").append(baseHTML);

				function createOberverObj(callBack){
					return new MutationObserver(function(mutations) {  
					  //mutations.forEach(function(mutation) {  

					   //if(mutation.type=="characterData"){
					   		callBack();
					  // }
					 // });      
				   })
				}

				function parseScriptXML(xml){
					
					if(xml){
						var autoDifinedScript = $("#autoDifinedScript"),
						name = xml.attr("id"), 
						scriptStr = "$(\"[data-ctrlId='"+name+"']\").off(\""+eventType.toLowerCase()+"\").on(\""+eventType.toLowerCase()+"\",function(){";
						if(!name) return;
						xml.find(eventType +" item").each(function(){
							var $this = $(this);
							var target = $this.find("target value"),temp = [],flag = true;

							if(!target.length) return;

							var funName = $this.find("actionType").html(),value = $(this).find("value").html(),objList = temp.join(",");
							for(var i=0;i<target.length;i++){
								var $v = $(target[i]),ctrlId = '$(".page [data-ctrlId=\''+$v.attr("ctrlId")+'\']")',v = $v.html();
								scriptStr += "runActionFunList['"+funName+"']("+ctrlId+",'"+v+"');";
							}
						
						})

						scriptStr +="});\r\n";

						
						if(autoDifinedScript.length > 0){
							var  oldStr = autoDifinedScript.html(), oldScript = getOldScriptString(oldStr,name);
							if(oldScript){
								autoDifinedScript.html(oldStr.replace(oldScript, scriptStr));
							}else{
								autoDifinedScript.append(scriptStr);
							}

						}else{
							$(".page").append("<script id='autoDifinedScript' type='text/javascript'>"+scriptStr+"</script>");
						}
						
						eval(scriptStr)
					}
				}


				function getOldScriptString(str,name){
					var startStr = "$(\"[data-ctrlId='"+name+"']\").off(\""+eventType.toLowerCase()+"\").on(\""+eventType.toLowerCase()+"\",function(){";
					return getOldHTML(startStr,"})",str);
				}


				function parseStyleXML(xml,type){
					
					var name = xml.attr("name"),arr = [],autoDifinedStyle =  $("head").find("#autoDifinedStyle"),moz = "";
				
					if(name){
						switch(styleType){
							case "base" :
								arr.push("[data-ctrlId='"+name+"']{");
								loopStyle.base(xml.find("base"),arr);
								arr.push("}"); 
								break;
							case "forged" :
								moz = ":hover";
								loopStyle.forged(xml.find("forged"),arr,name);
								break;
						}
						

						

						//loopStyle.keyframes(xml.find("keyframesList"),arr);
					}
					
					if(!autoDifinedStyle.length){
						arr.unshift("<style id='autoDifinedStyle'>");
						arr.push("</style>");
						$("head").append(arr.join(""));
					}else{
						var styleHtml =autoDifinedStyle.html(),oldStyle = getOldStyleString(styleHtml,name,moz);;
						
						if(oldStyle){
							styleHtml = styleHtml.replace(oldStyle,arr.join(""));
						}else{
							styleHtml = styleHtml+arr.join("");
						}
						
						autoDifinedStyle.html(styleHtml);
					}
					
					
				}
		

				function getOldStyleString(str,name,moz){
					var startStr = "[data-ctrlId='"+name+"']"+moz+"{";
					return getOldHTML(startStr,"}",str);
				}

				function getOldHTML(start,end,str){
					var  index = str.indexOf(start);
					if(index !=-1){
						var s = str.substr(index,start.length),
							send = str.substr(index+start.length),
							sIndex = send.indexOf(end),
							sStr = send.substr(0,sIndex+end.length);
						return (start+sStr);
					}else{
						return false;
					}
				}


				var	ctrlIndex = 0,
					actionIndex =0,
					defalut = {
						module : "F",//F:嵌入式 M:弹出式,
						save :　function(){},
						delete :　function(){}
					},
					styleType = "base",
					eventType = "Click",
					
					controlList = {
						DEFAULT : function(){
							var ctrl = {
									attrs :{},
									actions : actionFunList
								};	

								(function(){
								for(let i in attrFunc){
									if(i !='title'){

										ctrl.attrs[i] = function($ctrl){
											if(i == "outWidth" || i == "outHeight"){
												$ctrl = $ctrl.parent();
											}
											attrFunc[i]($ctrl);
										}
									}
								}

							})();
								return {
									getCtrl : function(){
										return ctrl;
									},

									setAction : function(){

									},

								}
						},

						PAGE : function(){
							var ctrl = {
									attrs :{
										'title' : function(ctrl){
											
											$(".setTitle input").val(ctrl.prev().find('.titleText').html());
											$(".setTitle input").keyup(function(event) {
												ctrl.prev().find('.titleText').html($(this).val());	
											});	

										
										}
									},
									actions : actionFunList
								};	

								return {
									getCtrl : function(){
										return ctrl;
									},

									setAction : function(){

									},

								}
						},

						defalutText : function(){
							var ctrl = {
									attrs :attrFunc,
									actions : actionFunList
								};	

								return {
									getCtrl : function(){
										return ctrl;
									},

									setAction : function(){

									},

								}
						},

						UEBOX : function(){
							
							var ctrl = {
									title : 'UEBOX',
									html : '<div class="ctrl" ctrl-type="UEBOX"><div class="ctrlHandel"></div><div  class="ctrlContent">UEBOX</div></div>',
									attrs : {
										"fontSize":function($ctrl){
											attrFunc['fontSize']($ctrl.find(".ctrlContent"));
										},
										width : function($ctrl){
											attrFunc['width']($ctrl);
										},
										height : function($ctrl){
											attrFunc['height']($ctrl);
										},

										margin : function($ctrl){
											attrFunc['margin']($ctrl);
										},
										padding : function($ctrl){
											attrFunc['padding']($ctrl);
										},

										borderWidth : function($ctrl){
											attrFunc['borderWidth']($ctrl);
										},
									},
									actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function($ctrl){
									var type = $ctrl.attr("uebox-type"),guid = $ctrl.attr("data-GUID"),newCtrl = $(ctrl.html),xCode =$ctrl.attr("xCode");

									$ctrl.replaceWith(newCtrl.attr({"uebox-type":type,"data-GUID":guid,"data-ctrlId":++ctrlIndex}));

									newCtrl.find(".ctrlContent").html(UEBOX[type]["html"](newCtrl.find(".ctrlContent"),guid, xCode));

									UEBOX[type]["init"](newCtrl.find(".ctrlContent >div"),xCode,guid);

									$("[data-GUID="+guid+"]",$("#left")).addClass('AddToPage').css("display","none");

									newCtrl.find(">.ctrlContent  >div").addClass("UeBoxSortable");
									UEditiorSortable($(".UeBoxSortable"),function(ctrl){
										if(ctrl.hasClass("fileddiv")||ctrl.hasClass("UEBOXCtrl")){
												return true;
											}
											ctrl.css({
												float:"left",
												width:"100%"
											}).addClass("UEBOXCtrl");
											//ctrl.find(".ctrlBox").sortable("option","connectWith",".left li,.page,.ctrlBox,.UeBoxSortable");

											ctrl.find(".ctrlBox").sortable("destroy");
											ctrl.find(".ctrlBox").sortable({
												connectWith : ".ctrlList li,.UeBoxSortable,.page,.ctrlBox",
												placeholder : "ctrl-placeholder"
											});
										},".UeBoxSortable");

									

									$(".ctrlList li").draggable("option","connectToSortable",".page,.UeBoxSortable");
									return newCtrl;
								},

								setAction : function(){

								},

								setData :　function(){
									
								}
							};
						},

						TEXT : function(){
							var ctrl = {
								title : '',
								html : '<div class="ctrl" ctrl-type="TEXT"><div class="ctrlHandel"></div><div  class="ctrlContent"><p   style="width:100%;height:100%">这是文本</p></div></div>',
								attrs : {
									"outWidth" : function($ctrl){
										attrFunc['outWidth']($ctrl);
									},
									"width":function($ctrl){
										attrFunc['width']($ctrl);
									},

									"outHeight" : function($ctrl){
										attrFunc['height']($ctrl);
									},
									"height":function($ctrl){
										attrFunc['height']($ctrl.find(".ctrlContent"));
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function($ctrl){
										attrFunc['padding']($ctrl);
									},
									"color":function($ctrl){
										attrFunc['color']($ctrl.find(".ctrlContent"));
									},
									"fontSize":function($ctrl){
										attrFunc['fontSize']($ctrl.find(".ctrlContent"));
									},
									"fontFamily":function($ctrl){
										attrFunc['fontFamily']($ctrl);
									},

									"align" : function($ctrl){
										attrFunc['align']($ctrl);
									},
									"background":function($ctrl){
										attrFunc['background']($ctrl);
									},
									"borderColor":function($ctrl){
										attrFunc['borderColor']($ctrl);
									},
									"borderStyle":function($ctrl){
										attrFunc['borderStyle']($ctrl);
									},
									"borderWidth":function($ctrl){
										attrFunc['borderWidth']($ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(ctrl){
									ctrl.dblclick(function(){
										var val = $(this).find(".ctrlContent >p").html().replace(/<br>/g,'\n'),h = $(this).height();

										$(this).find(".ctrlContent >p").replaceWith("<textarea  class='editText'   style='width:100%;height:"+h+"px' >"+val+"</textarea>");
										$(".editText").focus().show();
									});

									ctrl.on("blur",".editText",function(){
										var val = $(this).val(),rex = /\n/g;
										$(this).replaceWith("<p  style='width:100%;height:100%'>"+val.replace(rex,"<br/>")+"</p>");
									});
								},

								setAction : function(){

								},

								setData :　function(){
									
								}
							};
							
						},

						TEXTBOX :function() {
							var ctrl = {
								title: '文本框',
								html : '<div class="ctrl" ctrl-type="TEXTBOX"><div class="ctrlHandel"></div><div class="ctrlContent"><label class="ctrlTitle">文本框</label><div class="ctrlMain"><input type="text" class="form-control" /></div></div></div>',
								attrs : {
									"title" : function(ctrl){
										attrFunc['title'](ctrl);
									},
									"width":function(ctrl){
										attrFunc['width'](ctrl,function(){

										});
									},
									"height":function(ctrl){
										attrFunc['height'](ctrl.find(".ctrlContent input"));
									},
									
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function(ctrl){
										attrFunc['padding'](ctrl);
									},
									"color":function(ctrl){
										attrFunc['color'](ctrl.find(".ctrlContent"));
									},
									"fontSize":function(ctrl){
										attrFunc['fontSize'](ctrl.find(".ctrlContent input"));
									},
									"fontFamily":function(ctrl){
										attrFunc['fontFamily'](ctrl);
									},
									"background":function(ctrl){
										attrFunc['background'](ctrl);
									},
									"borderColor":function(ctrl){
										attrFunc['borderColor'](ctrl);
									},
									"borderStyle":function(ctrl){
										attrFunc['borderStyle'](ctrl);
									},
									"borderWidth":function(ctrl){
										attrFunc['borderWidth'](ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(ctrl){
									
								},

								setAction : function(ctrl){

								},

								setData :　function(ctrl){
									
								}
							};
						},
						DROPDOWN : function(){
							var ctrl = {
								title : '下拉框',
								html : '<div class="ctrl" ctrl-type="DROPDOWN"><div class="ctrlHandel"></div><div class="ctrlContent"><label class="ctrlTitle">下拉框</label> <div class="ctrlMain"><select  class="form-control" ><option value="">选项1</option></select></div></div></div>',
								attrs : {
									"title" : function(ctrl){

									},
									"width":function(ctrl){
										attrFunc['width'](ctrl);
									},
									"height":function(ctrl){
										attrFunc['height'](ctrl.find(".ctrlContent select"));
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function(ctrl){
										attrFunc['padding'](ctrl);
									},
									"color":function(ctrl){
										attrFunc['color'](ctrl);
									},
									"fontSize":function(ctrl){
										attrFunc['fontSize'](ctrl);
									},
									"fontFamily":function(ctrl){
										attrFunc['fontFamily'](ctrl);
									},
									"background":function(ctrl){
										attrFunc['background'](ctrl);
									},
									"borderColor":function(ctrl){
										attrFunc['borderColor'](ctrl);
									},
									"borderStyle":function(ctrl){
										attrFunc['borderStyle'](ctrl);
									},
									"borderWidth":function(ctrl){
										attrFunc['borderWidth'](ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(){
									
								},

								setAction : function(){

								},

								setData :　function(){
									
								}
							}
						},
						
						IMG : function(){
							var ctrl = {
								title :　'',
								html  :  '<div class="ctrl" ctrl-type="IMG"><div class="ctrlHandel"></div><img src="img/uni_logo.png" alt="defaultImg"></div>',
								attrHTML : {
									//changeIMG : '<div class="setAttr setReplaceIMG"><lable class="attrTitle">replaceIMG:</lable><div class="attrContent"><input type="file" id="UEditor_upload"><button class="replaceIMG">changeIMG</button></div></div>'
								},
								attrs :  {
									changeIMG : function($ctrl){
										$("#UEditor_upload").change(function(){
											var  file = this.files[0],
												 reader = new FileReader(file);
														//检验用户是否选则是图片文件
												if(file.type.split("/")[0] !== "image"){
													util.toast("You should choose an image file");
													return;
												} 
												reader.onload = function(event) {
													var base64 = event.target.result;
													$ctrl.find("img").attr("src",base64);
												} 
												reader.readAsDataURL(file);
										});
										
									},

									"outWidth" : function($ctrl){
										attrFunc['outWidth']($ctrl);
									},

									"width":function($ctrl){
										attrFunc['width']($ctrl.find("img"));
									},

									"outHeight" : function($ctrl){
										attrFunc['outHeight']($ctrl);
									},

									"height":function($ctrl){
										attrFunc['height']($ctrl.find("img"),0,$ctrl.height());
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function($ctrl){
										attrFunc['padding']($ctrl,0,$ctrl.width());
									},

									"borderRadius" : function($ctrl){
										attrFunc['borderRadius']($ctrl.find("img"));
									},
									"overflow" : function($ctrl){
										attrFunc['overflow']($ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
										return ctrl;
								},

								init : function(ctrl){
									
									var newCtrl = $('<div class="ctrl" ctrl-type="IMG"><div class="ctrlHandel"></div></div>');
									selectedCtrl(newCtrl);
									newCtrl.dblclick();
									return newCtrl;
								}
							}

						},
						BUTTON : function(){
							
							var ctrl = {
								title: '',
								html : '<div class="ctrl" ctrl-type="BUTTON"><div class="ctrlHandel"></div><button class="ctrlContent ">按钮</button></div>',
								attrs : {
									"width":function(ctrl){
										attrFunc['width'](ctrl);
									},
									"height":function(ctrl){
										attrFunc['height'](ctrl.find(".ctrlContent"));
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function(ctrl){
										attrFunc['padding'](ctrl);
									},
									"color":function(ctrl){
										attrFunc['color'](ctrl);
									},
									"fontSize":function(ctrl){
										attrFunc['fontSize'](ctrl.find(".ctrlContent"));
									},
									"fontFamily":function(ctrl){
										attrFunc['fontFamily'](ctrl);
									},
									"background":function(ctrl){
										attrFunc['background'](ctrl);
									},
									"borderColor":function(ctrl){
										attrFunc['borderColor'](ctrl);
									},
									"borderStyle":function(ctrl){
										attrFunc['borderStyle'](ctrl);
									},
									"borderWidth":function(ctrl){
										attrFunc['borderWidth'](ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(){
									
								},

								setAction : function(){

								},

								setData :　function(){
									
								}
							}
						},
						
						CHECKBOX : function(){
							var ctrl = {
								title : '复选框',
								html : '<div class="ctrl" ctrl-type="CHECKBOX"><div class="ctrlHandel"></div><div class="ctrlContent"><label class="ctrlTitle">复选框</label><div class="ctrlMain checkbox"><label><input type="checkbox" >选项1</label><label><input type="checkbox">选项2</label></div></div></div>',
								attrs : {
									"title" : function(ctrl){

									},
									"width":function(ctrl){
										attrFunc['width'](ctrl);
									},
									"height":function(ctrl){
										attrFunc['height'](ctrl.find(".ctrlContent"));
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function(ctrl){
										attrFunc['padding'](ctrl);
									},
									"color":function(ctrl){
										attrFunc['color'](ctrl);
									},
									"fontSize":function(ctrl){
										attrFunc['fontSize'](ctrl);
									},
									"fontFamily":function(ctrl){
										attrFunc['fontFamily'](ctrl);
									},
									"background":function(ctrl){
										attrFunc['background'](ctrl);
									},
									"borderColor":function(ctrl){
										attrFunc['borderColor'](ctrl);
									},
									"borderStyle":function(ctrl){
										attrFunc['borderStyle'](ctrl);
									},
									"borderWidth":function(ctrl){
										attrFunc['borderWidth'](ctrl);
									}
								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(){
									
								},

								setAction : function(){

								},

								setData :　function(){
									
								}
							}
						},
						BOX : function(){

							function setAttrOnload(obj,css){
								obj.attr("data-onload",css);
							}

							function delAttrOnload(obj){
								obj.removeAttr("data-onload");
							}

							function addAttrOnload(obj,css){
								obj.attr("data-onload",css);
							}

							function getAttrOnload(obj){
								return obj.attr("data-onload");
							}



							var ctrl = {
								title: '',
								html : '<div class="ctrl" ctrl-type="BOX"><div class="ctrlHandel"></div><div class="ctrlContent " style="display:flex;flex-wrap:wrap;height:100%"><div class="ctrlBox" style="height:100%;width:100%" ctrlBoxType="1" ></div><div class="ctrlBoxSplitLine"></div><div class="ctrlBox ctrlBox2" style="display:none;height:100%" ctrlBoxType="2"></div><div class="ctrlBoxSplitLine"></div><div class="ctrlBox ctrlBox3" style="display:none;height:100%"  ctrlBoxType="3"></div><div class="ctrlBoxSplitLine"></div><div class="ctrlBox ctrlBox4" style="display:none;height:100%"  ctrlBoxType="4"></div></div></div>',
								attrHTML :{
									boxtype   : '<div class="setAttr setBoxType"><lable class="attrTitle">type:</lable><div class="attrContent" style="display:flex"><div class="typeList" type="1"></div><div class="typeList" type="2">|</div><div class="typeList" type="3">||</div><div class="typeList" type="4">|||</div></div></div>',
									boxList   : '<div class="setAttr setBoxList" style="display:none"><lable class="attrTitle">boxList:</lable><div class="attrContent" style="display:flex"><div class="typeList" type="1"></div><div class="typeList" type="2"></div><div class="typeList" type="3"></div><div class="typeList" type="4"></div></div></div>',
									splitWidth : '<div class="setAttr setBoxSplitWidth"><lable class="attrTitle">splitWidth:</lable><div class="attrContent"></div></div>'
								},
								attrs : {
									boxtype : function(ctrl){
										
										$(".setBoxType").find(".attrContent .typeList[type='"+ctrl.find(">.ctrlContent >.ctrlBox:visible").length+"']").addClass('boxTypeSelect');
										$(".setBoxType .typeList").click(function(){
											$(".setBoxType .boxTypeSelect").removeClass('boxTypeSelect');
											$(this).addClass('boxTypeSelect');
											var type = $(this).attr("type");
											ctrl.find(".ctrlBox").show();
											switch(type){
												case "1":   ctrl.find('>.ctrlContent >[ctrlBoxType="1"]').css({"width":ctrl.width()+"px",height:"100%"});
															addAttrOnload(ctrl.find('>.ctrlContent >[ctrlBoxType="1"]'),'$(this).css({width:$(this).parent().width()+"px"})');
														    $(".setAttr.setBoxList").hide();
														    ctrl.find(">.ctrlContent >.ctrlBox2,>.ctrlContent >.ctrlBox3,>.ctrlContent >.ctrlBox4").css({width:"0px",height:"0px"}).attr("data-onload",'$(this).css({height:"0px"})');
														    ctrl.find(">.ctrlContent >.ctrlBoxSplitLine").hide();
														    break;

												case "2" :  
															var $ctrlBoxType1 = ctrl.find('>.ctrlContent >[ctrlBoxType="1"]'),$ctrlBoxType2 = ctrl.find('>.ctrlContent >[ctrlBoxType="2"]'),$qt = ctrl.find(">.ctrlContent >.ctrlBox3,>.ctrlContent >.ctrlBox4");
															if(getAttrOnload($ctrlBoxType1)){
																$ctrlBoxType2.css({"width":((ctrl.width()-1*4)/2)+"px",height:"100%"});
																addAttrOnload($ctrlBoxType2,'$(this).css({width:(($(this).parent().width()-1*4)/2)+"px"})');
																$ctrlBoxType1.css("width",((ctrl.width()-1*4)/2)+"px");
																delAttrOnload($ctrlBoxType1);
															}else{
																$ctrlBoxType2.css({"width":((ctrl.width()-1*4)/2)+"px",height:"100%"}).attr("data-onload",'$(this).css({width:(($(this).parent().width()-1*4)/2)+"px"})');
																addAttrOnload($ctrlBoxType2,'$(this).css({width:(($(this).parent().width()-1*4)-'+$ctrlBoxType1.width()+')+"px"})');
															}

															$(".setAttr.setBoxList").show();
															$(".setAttr.setBoxList").find("[type='3'],[type='4']").hide();
															$(".setAttr.setBoxList").find("[type='1'],[type='2']").show();
															
															
															$qt.css({width:"0px",height:"0px"});
															addAttrOnload($qt,'$(this).css({height:"0px"})');
															ctrl.find(">.ctrlContent >.ctrlBoxSplitLine").hide();
															ctrl.find(">.ctrlContent >.ctrlBox2").prev().show();
															
															break;

												case "3" :  

															ctrl.find(">.ctrlContent >.ctrlBox").css({"width":((ctrl.width()-2*4)/3)+"px",height:"100%"}).attr("data-onload",'$(this).css({width:(($(this).parent().width()-2*4)/3)+"px"})');
															$(".setAttr.setBoxList").show();
															ctrl.find(">.ctrlContent .ctrlBox4").hide();
															$(".setAttr.setBoxList").find("[type='4']").hide();
															ctrl.find(">.ctrlContent >.ctrlBox3").css("border-right","0px");
															$(".setAttr.setBoxList").find("[type='3'],[type='1'],[type='2']").show();
															ctrl.find(">.ctrlContent >.ctrlBoxSplitLine").show();
															ctrl.find(">.ctrlContent >.ctrlBox4").prev().hide();
															break;

												case "4" :  ctrl.find(">.ctrlContent >.ctrlBox").css({"width":((ctrl.width()-3*4)/4)+"px",height:"100%"}).attr("data-onload",'$(this).css({width:(($(this).parent().width()-3*4)/4)+"px"})');
															$(".setAttr.setBoxList").show();
															$(".setAttr.setBoxList").find("[type='3'],[type='1'],[type='2'],[type='4']").show();
															ctrl.find(">.ctrlContent >.ctrlBoxSplitLine").show();
															break;
											}
										})
									},

									"boxList" : function(ctrl){
										var t = this;
										if(ctrl.find(">.ctrlContent >.ctrlBox:visible").length>1){
											$(".setAttr.setBoxList").show();
										}
										$(".setAttr.setBoxList .typeList").click(function(){
											var type = $(this).attr("type"),$ctrlBoxItem = ctrl.find(">.ctrlContent >[ctrlboxtype='"+type+"']");
											if($(this).hasClass("boxTypeSelect")){
												$(this).removeClass("boxTypeSelect");
												$ctrlBoxItem.removeClass("selectCtrlBoxItem");
											}else{
												$(this).addClass("boxTypeSelect");
												$ctrlBoxItem.addClass("selectCtrlBoxItem");
											}

											var newCtrl = ctrl.find(">.ctrlContent >.selectCtrlBoxItem");
											if(newCtrl.length == 0){
												newCtrl = ctrl;
											}

											for(var o in t){
												if($.inArray(o,["boxList","boxtype","margin","width","height"])<=-1){
													t[o](newCtrl);
												}
											}
										});


									},

									"splitWidth" : function(ctrl){

										$(".setBoxSplitWidth .attrContent").UESlider({min:0,max:10,value:4,unit:false,step:1,change:function(value){
												var sw = ctrl.find(".ctrlBoxSplitLine:first").width(); 
												ctrl.find(".ctrlBoxSplitLine").css("width",value);
												ctrl.find(".ctrlBoxSplitLine").each(function(){
													var $O = $(this).next(),w =( $O.width()-(parseInt(value)-sw))+"px";
													console.log($O.width(),parseInt(value)-parseInt(sw),value,sw);
													$O.css({"width":w});
													//addAttrOnload();
												});
										}});

									}, 
									"width":function(ctrl){
										attrFunc['width'](ctrl);
									},
									"height":function(ctrl){
										attrFunc['height'](ctrl);
									},
									"margin":function($ctrl){
										attrFunc['margin']($ctrl);
									},
									
									"padding":function(ctrl){
										attrFunc['padding'](ctrl);
									},
									"color":function(ctrl){
										attrFunc['color'](ctrl);
									},
									"fontSize":function(ctrl){
										attrFunc['fontSize'](ctrl);
									},
									"fontFamily":function(ctrl){
										attrFunc['fontFamily'](ctrl);
									},
									"background":function(ctrl){
										attrFunc['background'](ctrl);
									},
									"borderColor":function(ctrl){
										attrFunc['borderColor'](ctrl);
									},
									"borderStyle":function(ctrl){
										attrFunc['borderStyle'](ctrl);
									},
									"borderWidth":function(ctrl){
										attrFunc['borderWidth'](ctrl);
									},
									"borderRadius" : function(ctrl){
										attrFunc['borderRadius'](ctrl);
									},
									overflow : function(ctrl){
										attrFunc['overflow'](ctrl);
									}


								},
								actions : actionFunList
							};

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function(ctrl){
									this.runInit(ctrl);
									addAttrOnload(ctrl.find('>.ctrlContent >[ctrlBoxType="1"]'),"$(this).css('width','100%')");
									UEditiorSortable(ctrl.find(".ctrlBox"));
								},

								runInit : function(ctrl){
										ctrl.find(">.ctrlContent >.ctrlBoxSplitLine").on("mousedown",function(e){
										var event = e || window.event,$this = $(this),$next = $this.next(),$prev = $this.prev(),pw = $prev.width(),nw = $next.width(),x = event.clientX;
										$(document).on("mousemove.ctrlBoxWidth",function(event){
											var event = event || window.event,xx = event.clientX,w = xx -x;
												if(pw+w >= 0 && nw-w >= 0 ){
													$prev.css("width",(pw+w)+'px');
													$next.css("width",(nw-w)+'px');
												}
												return false;
										})
									});

									$(document).on("mouseup",function(){
										$(document).off("mousemove.ctrlBoxWidth");	
										return true;								
									});
								},
								setAction : function(){

								},

								setData :　function(){
									
								}
							}
						},

						SPLIT : function(){
							var ctrl = {
								title : '',
								html : '<div class="ctrl" ctrl-type="SPLIT" ><div class="ctrlHandel"></div><div class="ctrlContent" style="height:600px"></div></div>',
								attrHTML : {
									splitType : '<div class="setAttr setSplitType"><div class="attrTitle" style="float:left">类型:</div><div class="attrContent"><div class="splitTypeItem"><input type="radio" title="横向" name="splitType" splitType="s" /><div class="s-split"></div></div><div class="splitTypeItem splitTypeItemSelect"><input type="radio" name="splitType" splitType="w" title="竖向" checked/><div class="w-split"></div></div></div></div>',
									sizeType : '<div class="setAttr setSizeType"><label class="attrTitle">尺寸类型:</label><div class="attrContent"><select class="sizeType"><option value="%">百分比</option><option value="all" selected>固定值</option><option value="prev" >左(上)固定值</option><option value="next" >右(下)固定值</option></select></div></div>',
								},
								attrs : {
									splitType : function($ctrl){
										$(".setSplitType [name='splitType']").change(function(event) {
											$ctrl.attr("data-splitType",$(this).attr("splitType"));
											$(".splitTypeItem").removeClass("splitTypeItemSelect");
											$(this).closest('.splitTypeItem').addClass('splitTypeItemSelect');
											refSplit($ctrl);
										});
									},

									height : function($ctrl){
										var ctrlContent = $ctrl.find(">.ctrlContent"), max = $ctrl.parent().height(),defalutVlaue = parseInt(ctrlContent.css("height"),10);
										$(".setHeight .attrContent").UESlider({min:200,max:max,value:defalutVlaue,change:function(value){
											ctrlContent.css("height",value);
										}});
									},

									width : function($ctrl){
										var ctrlContent = $ctrl.find(">.ctrlContent"), max = $ctrl.parent().width(),defalutVlaue = parseInt(ctrlContent.css("width"),10);
										$(".setWidth .attrContent").UESlider({min:100,max:max,value:defalutVlaue,unit:true,step:2,change:function(value){
												ctrlContent.css("width",value);
												$ctrl.css("width",value);
												defalutVlaue = value;
										}});
										
									},

									sizeType : function($ctrl){
										$(".setSizeType .sizeType").change(function(){
											$ctrl.attr("sizeType",$(this).val());
										});
									}
								},
								actions : actionFunList
							};

							function getSplitType($ctrl){
								return $ctrl.attr("data-splitType") || 'w';
							}

							function getSplit(ctrlContent){
								return ctrlContent.GetUESplit();
							}

							function refSplit($ctrl){
								var ctrlContent = $ctrl.find(">.ctrlContent"), split = ctrlContent.GetUESplit(),c = split.config;
									c.splitType = getSplitType($ctrl);
									if(c.splitType == "s"){
										c.splitHeight = 4;
										c.prevHeight = ctrlContent.height()/2-2;
									}else{
										c.splitWidth =4; 
										c.prevWidth = ctrlContent.width()/2-2;
									}
									
									$(split.splitDom).css({cursor: c.splitType+"-resize"}) 
									split.setSplit();
							}

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function($ctrl){
									var split = $ctrl.find('>.ctrlContent').height($ctrl.parent().height()-2).AddUESplit({
										splitType : "w",
										//borderWidth : 1,
										//borderColor : '#ff0000'
									});

									split.prevDom.addClass('ctrlBox');
									split.nextDom.addClass('ctrlBox');
									UEditiorSortable($ctrl.find(".ctrlBox"));
								},

								setAction : function(){

								},

								setData :　function(){

									
							}
						}
						},

						LIST : function(){
							var ctrl = {
									title      : "",
									html       : "<div class='ctrl' ctrl-type = 'LIST'><div class='ctrlHandel'></div><div class='ctrlContent' '></div></div>",
									attrHTML   : {
										column : "<div class='setAttr setColumn'><lable class='attrTitle'>column:</lable><div class='attrContent'><select class='column' style='width:120px;height:30px;outline:none;border-radius:4px'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option></select></div></div>", DataSource : "<div class='setAttr setDataSource'><lable class='attrTitle'>DataSource:</lable><div class='attrContent'><span></span><input type='button' value='选择数据源' style='    width: 120px; height: 30px; border: 1px solid #00a6fa; background: #00a6ff; color: #fff; border-radius: 4px; cursor: pointer;'></div></div>",
									},
									attrs      : {
										DataSource : function($ctrl){
											$(".setDataSource input").click(function(){
												var c = $ctrl.find(">.ctrlContent").UEList().config,dp = c.dataType;
												getDataSourceList();
												$(".pagePanelBox .panelSure").attr("class","panelSure DataListCtrl editorDataListCtrl");
												getBlog(function(d){
													blogBack(d,function(){

														for(var t in dp){
															var li = $(".xbyl-fieldList").find("."+t).addClass("selectedFieldItem");
															if(dp[t]["title"]){
																li.find(".titleSwitch input[value='YES']").prop("checked",true);
																li.find(".fieldTitleText").show().find("input").val(dp[t]["title"]);
															}

															li.find("select option[value='"+dp[t].type+"']").prop("selected",true);
														}
													})
												});
												$(".panelNavList li[data-path='"+c["data-path"]+"']").addClass("panelNavActive");
												$($(".panelNavList li[data-path='"+c["data-path"]+"']").attr("for")).show();

											});
										},
										column : function($ctrl){
											$(".setAttr .column").change(function(){
												$ctrl.find(">.ctrlContent >.dataBox").css({
													width:((1/parseInt($(this).val()))*100)+"%"
												});
											});
										},

										background : function($ctrl){
											attrFunc['background']($ctrl);
										},

										color : function($ctrl){
											attrFunc['color']($ctrl);
										},

										fontSize : function($ctrl){
											attrFunc['fontSize']($ctrl);
										},

										fontFamily : function($ctrl){
											attrFunc['fontFamily']($ctrl);
										}

										
									},
									actions : actionFunList
							};

							function sortStopCallback(drag,$this,$ctrl){
								if(drag.attr("data-type")){
									addCtrl(drag);
								}

								var item = $this.clone(),dataID = $this.attr("data-id"),dataField = drag.attr("data-field");
									item.find(".ctrlBox").addClass('fieldBox').removeClass('ctrlBox');
									item.find(".ctrlSelected").removeClass("ctrlSelected");
									item.attr("data-id","#fieldKey#");
									item.find("[data-field]").each(function(){
										var field = $(this).attr("data-field"),
										    fieldText = $(this).find(".filedText");
										    if(fieldText.hasClass('img')){
										    	fieldText.attr("src","#"+field+"#");
										    }else{
										    	fieldText.html("#"+field+"#");
										    }
									});
								
								$ctrl.html($ctrl.data("ueList").fillData(item[0].outerHTML));

								var $fieldList = $ctrl.find("[data-id='"+dataID+"']");
								if(dataField){
									$fieldList.find("[data-field='"+dataField+"']").click();
								}else{
									$fieldList.find("[data-ctrlId='"+drag.attr("data-ctrlId")+"']").click();
								}
								
								itemSort($ctrl);
							}

							function itemSort($ctrl){
								$(".fieldList",$ctrl).sortable({
									placeholder : "ctrl-placeholder",
									connectWith : ".fieldBox,.left li",
									axis : "y",
									stop: function(e,ui){
										sortStopCallback(ui.item,$(this),$ctrl);
										$(".fieldBox",$ctrl).sortable({
											placeholder : "ctrl-placeholder",
											connectWith : ".fieldList,.left li",
											stop : function(e,ui){
												sortStopCallback(ui.item,$(this).closest(".fieldList"),$ctrl);
											}
										});
									}
								});
							};

							return {
								getCtrl : function(){
									return ctrl;
								},


								init : function($ctrl,config,data){
									if(data){
										config.data = data;
									}
									
									$ctrl = $(this.getCtrl().html);
									$ctrl.find(">.ctrlContent").UEList(config);
									
									$ctrl.find("[data-field]").attr("ctrl-type","LISTITEM");
									$ctrl.find(".fieldList").attr("ctrl-type","LISTITEM");
									itemSort($ctrl.find(">.ctrlContent"));

									$(".ctrlList li").draggable("option","connectToSortable",".page,.fieldList");
									
									return $ctrl;
								},
								setAction : function(){},
								setData : function(){

								}
							}
						},

						LISTITEM : function(){
							var ctrl = {
								attrs : {
								},
								actions : actionFunList
							};

							(function(t){
								for(let i in attrFunc){
									if(i !='title'){
										ctrl.attrs[i] = function($ctrl){
											attrFunc[i](getCtrlList($ctrl));
										}
									}
								}

							})(attrFunc);

							function getCtrlList($ctrl){
								var o = $ctrl,$c = $ctrl.closest('.ctrlContent');
								if(o.hasClass('fieldList')){
									o = $c.find(">.fieldList");
								}else{
									let dataField = $ctrl.attr("data-field"),dataCtrlId = $ctrl.attr("data-ctrlId");
									if(dataField){
										o = $c.find("[data-field='"+dataField+"']");
									}else{
										o = $c.find("[data-ctrlId='"+dataCtrlId+"']");
									}
								}


								return o ;
							}

							return {
								getCtrl : function(){
									return ctrl;
								} 
							}
						},

						defineCtrl : function(){
							var ctrl = {
								title : "",
								html : "<div class='ctrl' ctrl-type = 'defineCtrl'><div class='ctrlHandel'></div><div class='ctrlContent' '></div></div>",
							}

							return {
								getCtrl : function(){
									return ctrl;
								},

								init : function($ctrl,config,data){
									var ctrl = config.ctrl;
									$ctrl = $(ctrl.html);

									return $ctrl;
								}
							}
						}
					},

				getSlider  = function(){
					return	"<div class='item'>\
							<div class='topRight' style='margin-left:33px;margin-top:5px;'>\
								<div class='setTop' style='display:inline-block;width:145px;'>\
									<lable class='attrTitle' style='width:80px'>top:</lable>\
									<div class='attrContent' style='width:60px'></div>\
								</div>\
								<div class='setRight' style='display:inline-block;width:145px;'>\
									<lable class='attrTitle' style='width:80px'>right:</lable>\
									<div class='attrContent' style='width:60px'></div>\
								</div>\
							</div>\
							<div class='bottomLeft' style='margin-left:33px;margin-top:5px;'>\
								<div class='setBottom' style='display:inline-block;width:145px;'>\
									<lable class='attrTitle' style='width:80px'>bottom:</lable>\
									<div class='attrContent' style='width:60px'></div>\
								</div>\
								<div class='setLeft' style='display:inline-block;width:145px;'>\
									<lable class='attrTitle' style='width:80px'>left:</lable>\
									<div class='attrContent' style='width:60px'></div>\
								</div>\
							</div>\
						</div>";
							
						
				},
				getCtrId = function(ctrl){
					return ctrl.attr("data-ctrlId");
				},

				setForgedValue = function(){

				},

				setBaseValue = function(){

				},

				setStyleValue = function(ctrl,attr,value){
						setXMLValue(ctrl,attr,styleType,value);
				},

				setXMLValue = function(ctrl,attr,type,value){
					ctrlXML = getCtrlXML(ctrl);
					if(type == "forged"){
						type = "forged > hover"
					}
					var target = findTarget(ctrlXML.find(" > "+type).attr("fill",true),attr);

					target.html(value);

				},

				findTarget = function(ctrlXml,attr){
					var $attr = ctrlXml.find(" > "+attr);
					if($attr.length){
						return $attr.attr("fill","true");
					}else{
						var attrArr = attr.split("-"),cxml = ctrlXml.find(">"+attrArr.shift()).attr("fill",true);
						if(attrArr.length > 0){
							return findTarget(cxml,attrArr.join("-"));
						}else{
							var newDom = $(document.createElement(attr));
							ctrlXml.append(newDom.attr("fill",true).html("defalut"));
							//console.error(attr+"  IS NEW attributes");
							return newDom;
						}
					}
				},

				getCtrlXML = function(ctrl){
					var ctrlId = addCtrlId(ctrl),ctrlXML = $xml.find("[name='"+ctrlId+"']");
					return ctrlXML.length >0 ? ctrlXML : (function(){
						var cXml = ctrlXmlTemplate.clone(true);
						$(cXml).attr("name",ctrlId)
						$xml.find("styleList").append(cXml);;
						return cXml;
					})();
				},

				attrFunc = {
					
					parent : function(ctrl){
						if(ctrl.hasClass("page")){
							$(".setParent").remove();
							return;
						}
						$(".setParent .parent").click(function(){
							selectedCtrl(ctrl.parent());
						});
					},

					title :　function(ctrl){
						$(".setTitle input").val(ctrl.find(".ctrlTitle").html());
						$(".setTitle input").keyup(function(event) {
							ctrl.find(".ctrlTitle").html($(this).val());	
						});						
					},

					display : function(ctrl){
						$(".setDisplay .display").find('option[value="'+ctrl.css("display")+'"]').prop("selected",true);
						$(".setDisplay .display").change(function(){
							setStyleValue(ctrl,"display",$(this).val());
						});
					},

					position : function(ctrl,min,max){
						var p = ctrl.css("position"),t = r = b = l = 0;
						max =max ? max : 999;min = min ? min : min==0 ? 0 : -999 ;
						$(".setPosition .position").find('option[value="'+p+'"]').prop("selected",true);
						$(".setPosition .position").change(function(){
							//ctrl.css("position",$(this).val());
							setStyleValue(ctrl,"position",$(this).val());
						});

						$(".setPosition").append(getSlider());
						if(p != 'static'){
							t = parseInt(ctrl.css("top"),10);
							r = parseInt(ctrl.css("right"),10);
							b = parseInt(ctrl.css("bottom"),10);
							l = parseInt(ctrl.css("left"),10);
						}
						$(".setPosition .setTop .attrContent").UESlider({min:min,max:max,slider:false,value:t,change:function(value){
							//ctrl.css("top",value);
							setStyleValue(ctrl,"top",value);
						}});

						$(".setPosition .setRight .attrContent").UESlider({min:min,max:max,slider:false,value:r,change:function(value){
							//ctrl.css("right",value);
							setStyleValue(ctrl,"right",value);
						}});

						$(".setPosition .setBottom .attrContent").UESlider({min:min,max:max,slider:false,value:b,change:function(value){
							// ctrl.css("bottom",value);
							setStyleValue(ctrl,"bottom",value);
						}});

						$(".setPosition .setLeft .attrContent").UESlider({min:min,max:max,slider:false,value:l,change:function(value){
							// ctrl.css("left",value);
							setStyleValue(ctrl,"left",value);
						}});
					},

					float : function(ctrl){
						$(".setFloat .float").find('option[value="'+ctrl.css("float")+'"]').prop("selected",true);
						$(".setFloat .float").change(function(){
							setStyleValue(ctrl,"float",$(this).val());
						});
					},
					outWidth : function(ctrl,min,max){
						$(".setoutWidth .attrContent").UESlider({min:0,max:ctrl.parent().width(),value:parseInt(ctrl.css("width"),10),unit:true,unitValue: "px",change:function(value){
							// ctrl.css("width",value);
							setStyleValue(ctrl,"width",value);
						}});
					},

					width : function(ctrl,min,max){

						$(".setWidth .attrContent").UESlider({min:0,max:ctrl.parent().width(),value:parseInt(ctrl.css("width"),10),unit:true,unitValue: "px",change:function(value){
							ctrl.css("width",value);
							//setStyleValue(ctrl,"width",value);
						}});
					},


					outHeight : function(ctrl,min,max){
						$(".setoutHeight .attrContent").UESlider({min:0,max:ctrl.parent().height(),value:parseInt(ctrl.css("height"),10),unit:true,change:function(value){
							// ctrl.css("height",value);
							setStyleValue(ctrl,"height",value);
						}});
					},

					height : function(ctrl,min,max){
						$(".setHeight .attrContent").UESlider({min:0,max:ctrl.parent().height(),value:parseInt(ctrl.css("height"),10),unit:true,change:function(value){
							 ctrl.css("height",value);
							//setStyleValue(ctrl,"height",value);
						}});
					},


					margin : function(ctrl,min,max){
						
						$(".setMargin .attrContent").UESlider({min:-100,max:100,value:parseInt(ctrl.css("margin"),10),change:function(value){
							// ctrl.css("margin",value);
							setStyleValue(ctrl,"margin",value);
							$(".setMargin .setTop .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setMargin .setRight .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setMargin .setBottom .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setMargin .setLeft .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
						}});

						$(".setMargin >.item").remove();
						$(".setMargin").append(getSlider());
						$(".setMargin .setTop .attrContent").UESlider({min:-100,max:100,slider:false,value:parseInt(ctrl.css("margin-top"),10),change:function(value){
							//ctrl.css("margin-top",value);
							setStyleValue(ctrl,"margin-top",value);
						}});

						$(".setMargin .setRight .attrContent").UESlider({min:-100,max:100,slider:false,value:parseInt(ctrl.css("margin-right"),10),change:function(value){
							//ctrl.css("margin-right",value);
							setStyleValue(ctrl,"margin-right",value);
						}});

						$(".setMargin .setBottom .attrContent").UESlider({min:-100,max:100,slider:false,value:parseInt(ctrl.css("margin-bottom"),10),change:function(value){
							//ctrl.css("margin-bottom",value);
							setStyleValue(ctrl,"margin-bottom",value);
						}});

						$(".setMargin .setLeft .attrContent").UESlider({min:-100,max:100,slider:false,value:parseInt(ctrl.css("margin-left"),10),change:function(value){
							//ctrl.css("margin-left",value);
							setStyleValue(ctrl,"margin-left",value);
						}});
					},

					padding : function(ctrl,min,max){
						
						$(".setPadding >.item").remove();
						$(".setPadding .attrContent").UESlider({min:min,max:max,value:parseInt(ctrl.css("padding"),10),change:function(value){
							//ctrl.css("padding",value);
							setStyleValue(ctrl,"padding",value);
							$(".setPadding .setTop .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setPadding .setRight .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setPadding .setBottom .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
							$(".setPadding .setLeft .attrContent").UESlider().setVlaue(value.replace(/\D/g,""));
						}});

						$(".setPadding").append(getSlider());
						$(".setPadding .setTop .attrContent").UESlider({min:min,max:max,slider:false,value:parseInt(ctrl.css("padding-top"),10),change:function(value){
							// ctrl.css("padding-top",value);
							setStyleValue(ctrl,"padding-top",value);
						}});

						$(".setPadding .setRight .attrContent").UESlider({min:min,max:max,slider:false,value:parseInt(ctrl.css("padding-right"),10),change:function(value){
							// ctrl.css("padding-right",value);
							setStyleValue(ctrl,"padding-right",value);
						}});

						$(".setPadding .setBottom .attrContent").UESlider({min:min,max:max,slider:false,value:parseInt(ctrl.css("padding-bottom"),10),change:function(value){
							// ctrl.css("padding-bottom",value);
							setStyleValue(ctrl,"padding-bottom",value);
						}});

						$(".setPadding .setLeft .attrContent").UESlider({min:min,max:max,slider:false,value:parseInt(ctrl.css("padding-left"),10),change:function(value){
							// ctrl.css("padding-left",value);
							setStyleValue(ctrl,"padding-left",value);
						}});
					},

					color :　function(ctrl,min,max){
						$(".setColor .attrContent").css("background",ctrl.css("color"));
						getColorPan($(".setColor .attrContent"),function(c){
							//ctrl.css("color",c);
							setStyleValue(ctrl,"color",c);
							$(".setColor .attrContent").css("background",c);
						});
					},

					fontSize : function(ctrl,min,max){
						$(".setFontSize .attrContent").UESlider({min:12,max:30,value:parseInt(ctrl.css("font-size"),10),change:function(value){
							//ctrl.css("font-size",value);
							setStyleValue(ctrl,"font-size",value);
						}});
					},

					fontFamily : function(ctrl,min,max){
						$(".setFontFamily .fontFamily").find('option[value='+ctrl.css("font-family")+']').prop("selected",true);
						$(".setFontFamily .fontFamily").change(function(event) {
							// ctrl.css("font-family",$(this).val());
							setStyleValue(ctrl,"font-family",$(this).val());
						});
					},
					align : function(ctrl){
						$(".setAlign .align").find('option[value="'+ctrl.css("align")+'"]').prop("selected",true);
						$(".setAlign .align").change(function(){
							setStyleValue(ctrl,"text-align",$(this).val());
						});
					},

					background : function(ctrl,min,max){
						$(".setBackground .colorBox").css("background",ctrl.css("background-color"));
						getColorPan($(".setBackground .colorBox"),function(c){
							//ctrl.css("background-color",c);
							setStyleValue(ctrl,"background-color",c);
							$(".setBackground .colorBox").css("background-color",c);
						});
					},

					borderColor : function(ctrl,min,max){
						$(".setBorderColor .colorBox").css("background-color",ctrl.css("border-color"));
						getColorPan($(".setBorderColor .colorBox"),function(c){
							// ctrl.css("border-color",c);
							setStyleValue(ctrl,"border-color",c);
							$(".setBorderColor .colorBox").css("background-color",c);
						});
					},

					borderStyle : function(ctrl,min,max){
						$(".setBorderStyle .borderStyle").find('option[value="'+ctrl.css("border-style")+'"]').prop("selected",true);
						$(".setBorderStyle .borderStyle")[0].onchange = function(event) {
							// ctrl.css("border-style",$(this).val());
							setStyleValue(ctrl,"border-style",$(this).val());
						};
					},

					borderWidth : function(ctrl,min,max){
						$(".setBorderWidth .attrContent").UESlider({min:0,max:100,value:parseInt(ctrl.css("border-width"),10),change:function(value){
							// ctrl.css("border-width",value);
							setStyleValue(ctrl,"border-width",value);
						}});
					},

					borderRadius : function(ctrl,min,max){
						var w = ctrl.width()/2,h = ctrl.height()/2;
						$(".setBorderRadius .attrContent").UESlider({min:0,max:w<h?w:h,value:parseInt(ctrl.css("border-radius"),10),unit:true,change:function(value){

							// ctrl.css("border-radius",value);
							setStyleValue(ctrl,"border-radius",value);
						}});
					},

					overflow : function(ctrl,min,max){
						$(".setOverflow .overflow").find('option[value="'+ctrl.css("overflow")+'"]').prop("selected",true);
						$(".setOverflow .overflow").change(function(event) {
							var v = $(this).val(),sv = v.split(" ");
							if(sv.length == 2){
								// ctrl.css("overflow-x",sv[0]);
								// ctrl.css("overflow-y",sv[1]);
								setStyleValue(ctrl,"overflow-x",sv[0]);
								setStyleValue(ctrl,"overflow-y",sv[1]);
							}else{
								// ctrl.css("overflow",v);
								setStyleValue(ctrl,"overflow-x",v);
								setStyleValue(ctrl,"overflow-y",v);
							}
						});
					},

					animation : function(ctrl){

					},


				},

				FontFamilyList = function () {
		            return [
			                { label: 'Arial',             action: "'style',{fontFamily:'Arial'           }", css: 'font-family:Arial' },
			                { label: 'Verdana',           action: "'style',{fontFamily:'Verdana'         }", css: 'font-family:Verdana' },
			                { label: 'Georgia',           action: "'style',{fontFamily:'Georgia'         }", css: 'font-family:Georgia' },
			                { label: 'Impact',            action: "'style',{fontFamily:'Impact'          }", css: 'font-family:Impact' },
			                { label: 'Georgia',           action: "'style',{fontFamily:'Georgia'         }", css: 'font-family:Georgia' },
			                { label: 'Tahoma',            action: "'style',{fontFamily:'Tahoma'          }", css: 'font-family:Tahoma' },
			                { label: 'Monaco',            action: "'style',{fontFamily:'Monaco'          }", css: 'font-family:Monaco' },
			                { label: 'Trebuchet MS',      action: "'style',{fontFamily:'Trebuchet MS'    }", css: 'font-family:Trebuchet MS' },
			                { label: 'Comic Sans MS',     action: "'style',{fontFamily:'Comic Sans MS'   }", css: 'font-family:Comic Sans MS' },
			                { label: 'Time News Roman',   action: "'style',{fontFamily:'Time News Roman' }", css: 'font-family:Time News Roman' },
			                { label: 'Courier New',       action: "'style',{fontFamily:'Courier New'     }", css: 'font-family:Courier New' },
			                { label: 'MingLiU',           action: "'style',{fontFamily:'MingLiU'         }", css: 'font-family:MingLiU' },
			                { label: 'PMingLiU',          action: "'style',{fontFamily:'PMingLiU'        }", css: 'font-family:PMingLiU' },
			                { label: 'MS UI Gothic',      action: "'style',{fontFamily:'MS UI Gothic'    }", css: 'font-family:MS UI Gothic' },
			                { label: 'Hei',               action: "'style',{fontFamily:'Hei'             }", css: 'font-family:Hei' },
			                { label: 'simhei',            action: "'style',{fontFamily:'simhei'          }", css: 'font-family:simhei' },
			                { label: 'YaHei',             action: "'style',{fontFamily:'YaHei'           }", css: 'font-family:YaHei' },
			                { label: '宋体',           	  action: "'style',{fontFamily:'宋体'            }", css: 'font-family:宋体' },
			                { label: '仿宋',              action: "'style',{fontFamily:'仿宋'            }", css: 'font-family:仿宋' },
			                { label: '黑体',              action: "'style',{fontFamily:'黑体'            }", css: 'font-family:黑体' },
			                { label: '楷体',              action: "'style',{fontFamily:'楷体'            }", css: 'font-family:楷体' },
			                { label: '华文行楷',          action: "'style',{fontFamily:'华文行楷'        }", css: 'font-family:华文行楷' },
			                { label: '华文新魏',          action: "'style',{fontFamily:'华文新魏'        }", css: 'font-family:华文新魏' },
			                { label: '华文隶书',          action: "'style',{fontFamily:'华文隶书'        }", css: 'font-family:华文隶书' },
			                { label: 'italic',            action: "'style',{fontFamily:'italic'          }", css: 'font-family:italic' },
		            ]
	   		 	},

				getFontFamilyList = function(){
					var fontFamily = FontFamilyList(),l = ['<select class="fontFamily">'];
					for(var i = 0; i<fontFamily.length;i++){
						l.push('<option value="'+fontFamily[i]['label']+'">'+fontFamily[i]['label']+'</option>');
					}
					return l.join('')+"</select>";
				}, 

				eachCtrlList = function(callBack){
					for(var value in ctrlList){
						var ctrlId = value,text = ctrlList[value]["ctrlType"]+ctrlId.split("_")[1];
						temp.push(template.replace("${ctrlId}",ctrlId).replace("${name}",text));
					}
				}

				attrHTML = {
					title       	: "<div class='setAttr setTitle'><lable class='attrTitle'>title:</lable><div class='attrContent'><input class='form-control'  placeholder='请输入标题'/></div></div>",
					width           : "<div class='setAttr setWidth'><lable class='attrTitle'>width:</lable><div class='attrContent'></div></div>",
					//outWidth        : "<div class='setAttr setoutWidth'><lable class='attrTitle'>outWidth:</lable><div class='attrContent'></div></div>",
					height          : "<div class='setAttr setHeight'><lable class='attrTitle'>height:</lable><div class='attrContent'></div></div>",
					//outHeight       : "<div class='setAttr setoutHeight'><lable class='attrTitle'>outHeight:</lable><div class='attrContent'></div></div>",
					margin          : "<div class='setAttr setMargin'><lable class='attrTitle'>margin:</lable><div class='attrContent'></div></div>",
					topMargin       : "<div class='setAttr setTopMargin'><lable class='attrTitle'>margin-top:</lable><div class='attrContent'></div></div>",
					rightMargin     : "<div class='setAttr setRightMargin'><lable class='attrTitle'>margin-right:</lable><div class='attrContent'></div></div>",
					bottomMargin    : "<div class='setAttr setBottomMargin'><lable class='attrTitle'>margin-bottom:</lable><div class='attrContent'></div></div>",
					leftMargin      : "<div class='setAttr setLeftMargin'><lable class='attrTitle'>margin-left:</lable><div class='attrContent'></div></div>",
					padding     	: "<div class='setAttr setPadding'><lable class='attrTitle'>padding:</lable><div class='attrContent'></div></div>",
					color       	: "<div class='setAttr setColor' ><lable class='attrTitle'>fontColor:</lable><div class='attrContent colorBox'><input type='text' style='opacity:0'></div></div>",
					fontSize    	: "<div class='setAttr setFontSize'><lable class='attrTitle'>fontSize:</lable><div class='attrContent'></div></div>",
					fontFamily  	: "<div class='setAttr setFontFamily'><lable class='attrTitle'>fontFamily:</lable><div class='attrContent'>"+getFontFamilyList()+"</div></div>",
					background  	: "<div class='setAttr setBackground'><lable class='attrTitle'>background:</lable><div class='attrContent colorBox'><input type='text' style='opacity:0'></div></div>",
					borderColor 	: "<div class='setAttr setBorderColor'><lable class='attrTitle'>borderColor:</lable><div class='attrContent colorBox'><input type='text' style='opacity:0'></div></div>",
					borderStyle 	: "<div class='setAttr setBorderStyle'><lable class='attrTitle'>borderStyle:</lable><div class='attrContent'><select class='borderStyle'><option value='solid'>solid</option><option value='none'>none</option><option value='dotted'>dotted</option><option value='dashed'>dashed</option><option value='double'>double</option><option value='inherit'>inherit</option></select></div></div>",
					borderWidth 	: "<div class='setAttr setBorderWidth'><lable class='attrTitle'>borderWidth:</lable><div class='attrContent'></div></div>",
					borderRadius	: "<div class='setAttr setBorderRadius'><lable class='attrTitle'>radius:</lable><div class='attrContent'></div></div>",
					overflow        : "<div class='setAttr setOverflow'><lable class='attrTitle'>overflow</lable><div class='attrContent'><select class='overflow'><option value='visible' selected>visible</option><option vlaue='auto'>auto</option><option vlaue='hidden'>hidden</option><option vlaue='scroll'>scroll</option><option vlaue='hidden auto'>hidden auto</option><option vlaue='hidden scroll'>hidden scroll</option><option vlaue='auto hidden'>auto hidden</option><option vlaue='scroll hidden'>scroll hidden</option><option vlaue='scroll auto'>scroll auto</option><option vlaue='auto scroll'>auto scroll</option></select></div></div>",
					display         : "<div class='setAttr setDisplay'><lable class='attrTitle'>display:</lable><div class='attrContent'><select class='display'><option value='inline'>inline</option><option value='block'>block</option><option value='inline-block'>inline-block</option><option value='none'>none</option></select></div></div>",
					align         : "<div class='setAttr setAlign'><lable class='attrTitle'>align:</lable><div class='attrContent'><select class='align'><option value='left'>left</option><option value='right'>right</option><option value='center'>center</option></select></div></div>",
					float         : "<div class='setAttr setFloat'><lable class='attrTitle'>float:</lable><div class='attrContent'><select class='float'><option value='left'>left</option><option value='right'>right</option><option value='inherit'>inherit</option><option value='none'>none</option></select></div></div>",
					position        : "<div class='setAttr setPosition'><lable class='attrTitle'>position:</lable><div class='attrContent'><select class='position'><option value='static'>static</option><option value='absolute'>absolute</option><option value='relative'>relative</option><option value='fixed'>fixed</option><option value='inherit'>inherit</option></select></div></div>",
					parent          : "<div class='setAttr setParent'><lable class='attrTitle'></lable><div class='attrContent'><button class='parent' style='width:60px;height:25px'>setParent</button></div></div>"
				},
				
				runActionFunList = {
					showHide : function(target,value){
						target[value](1000);

					},

					pageJump : function(){

					}
				},

				actionFunList = {
					showHide : function(ctrl,actionObj,value){
						var ctrlId = getCtrId(ctrl),temp = [],
						template = '<div class="optionItem" data-ctrlId="${ctrlId}"> <div class="checkBox" > <input type="checkBox" class="check" > </div> <div class="optionText">${name}</div> </div>';
						
						for(var value in ctrlList){
							var ctrlId = value,text = ctrlList[value]["ctrlType"]+ctrlId.split("_")[1];
							temp.push(template.replace("${ctrlId}",ctrlId).replace("${name}",text));
						}
						actionObj.find(".selectOption").html(temp.join(""));
						$(".palceholder",actionObj).click(function(){
							$(this).next().show(300);
						});
						$(".targer-select",actionObj).hover(function(){},function(){
							$(".selectOption",actionObj).hide(300);
						});
						$(".optionItem",actionObj).hover(function(){
							var $ctrl = $(".page [data-ctrlid='"+$(this).attr("data-ctrlid")+"']").addClass("chooseCtrl");
							//$ctrl.append("<div class='ctrl-mask' style='position:absolute;width:100%;height:100%;top:0px;left:0px;z-index:10;background:rgba(0,0,0,0.6)'></div>");
							
						},function(){
							$(".page [data-ctrlid='"+$(this).attr("data-ctrlid")+"']").removeClass("chooseCtrl");
							//$(".page [data-ctrlid='"+$(this).attr("data-ctrlid")+"'] .ctrl-mask").remove();
						})
						$(".checkBox .check",actionObj).change(function(){
							var $t = $(this),$options=$t.closest(".optionItem"),ctrlId = $options.attr("data-ctrlid"),ctrlName = $options.find(".optionText").text();
							var widgetAction = '<div class="widgetAction" data-ctrlId = "'+ctrlId+'"> <div class="radioList"> <div class="radioItem"> <input type="radio" name="'+ctrlId+'" value="show" checked> <div class="radioText showText ">Show</div> </div> <div class="radioItem"> <input type="radio" name="'+ctrlId+'" value="hide"> <div class="radioText hideText ">Hide</div> </div> </div> <div class="actionCtrl">'+ctrlName+'</div> <div class="delActionCtrl iconfont icon-close"></div></div>';
							if($t.is(":checked")){
								$t.prop("disabled","disabled").addClass("jinyong");
								$t.parent().addClass("iconfont icon-right yixuan")

								$t.closest(".actionContent").append(widgetAction);
								setActionXML(getOption(actionObj));
							}
						})

						actionObj.on("click",".delActionCtrl",function(){
							var widgetAction = $(this).closest(".widgetAction"),ctrlId = widgetAction.attr("data-ctrlid");
							widgetAction.remove();
							setActionXML(getOption(actionObj));
							$(".selectOption [data-ctrlid='"+ctrlId+"'] .checkBox",actionObj).removeClass("iconfont icon-right yixuan").find(".check").removeClass("jinyong").removeAttr("disabled").prop("checked",false);
						});

						actionObj.on("mouseover",".actionCtrl",function(){
							var $ctrl = $(".page [data-ctrlid='"+$(this).closest(".widgetAction").attr("data-ctrlid")+"']").addClass("chooseCtrl");
							//$ctrl.append("<div class='ctrl-mask' style='position:absolute;width:100%;height:100%;top:0px;left:0px;z-index:10;background:rgba(0,0,0,0.6)'></div>");
						
						});
					
						actionObj.on("mouseout",".actionCtrl",function(){
							$(".page [data-ctrlid='"+$(this).closest(".widgetAction").attr("data-ctrlid")+"']").removeClass("chooseCtrl");
							//var $ctrl = $(".page [data-ctrlid='"+$(this).closest(".widgetAction").attr("data-ctrlid")+"'] .ctrl-mask").remove();
						});

						actionObj.on("change",".radioItem input",function(){
							setActionXML(getOption(actionObj));
						});
						
						function getOption(actionObj){
							var a = $(".actionContent",actionObj).find(".widgetAction"),t = [];
							for(var i = 0; i < a.length; i++){
								var ai = $(a[i]);
								t.push({
									"ctrlId" : ai.attr("data-ctrlid"),
									"value"	 : ai.find(".radioItem input:checked").val()
								});
							}

							return {
								ctrl : ctrl,
								actionObj : actionObj,
								target : t
							}
						}
					},

					pageJump : function(){}
				},

				setActionXML = function(option){
					var ctrlId = getCtrId(option.ctrl),
						action_id = option.actionObj.attr("action_id"),
						target = option.target,
					ctrlActionXML = $actionXML.find("#"+ctrlId);
					var item = ctrlActionXML.find("[action_id='"+action_id+"']"),targetEvent =0,temp=[] ;
					for(var i = 0; i<target.length;i++){
						temp.push('<value ctrlId = "'+target[i]["ctrlId"]+'">'+target[i]["value"]+'</value>');
					}
					if(temp.length>0){
						item.find(eventType+ " target").html(temp.join(""));
					}
				},

				actionHTML = {
					showHide : '<div class="setAction setShowHide"> <div class="actionTop"> <lable class="actionTitle">Show OR Hide</lable> <span class="actionClose iconfont icon-close"></span> </div> <div class="actionContent"> <div class="widget"> <label class="ChooseWidget">目标对象</label> <div class="targer-select"> <div class="palceholder"> <span>选择目标元素</span><span class="iconfont icon-unfold1"></span> </div> <div class="selectOption"> <div class="optionItem"> <div class="checkBox iconfont icon-right"> <input type="checkBox" class="check"> </div> <div class="optionText">文本2</div> </div> </div> </div> </div> </div> </div>',
					pageJump : ''
				},

				loadAttr = function(ctrl){

					if(ctrl.length <= 0){
						$("#attrs .styleContent").empty();
						return;
					}
					var ctrlType = ctrl.attr("ctrl-type") ||　"DEFAULT",getCtrl = controlList[ctrlType]().getCtrl(),attrs = getCtrl.attrs,ctrlAttrHtml = getCtrl['attrHTML'] || {} ,attrStr = [];
					
					for(var key in attrs){
						attrStr.push(ctrlAttrHtml[key] || attrHTML[key]);
					} 

					
					$("#attrs .styleContent").html(attrStr.join(""));

					for(var key in attrs){
						attrs[key](ctrl);
					} 

					
					//$("#attrs .styleContent").append(attrHTML["parent"]);
					//attrFunc["parent"](ctrl);
					
				},

				restoreAction = function(ctrl){

					var ctrlId = getCtrId(ctrl),
						ctrlType = ctrl.attr("ctrl-type") ||　"DEFAULT",
					 	getCtrl = controlList[ctrlType]().getCtrl(),
					 	actions = getCtrl.actions,
					 	ctrlActionsHtml = getCtrl['actionHTML'] || {};

					 ctrlActionXML = $actionXML.find("#"+ctrlId);
					$(".itemBoxContent").empty();
					ctrlActionXML.children().each(function(){
						var tagName = $(this)[0].tagName,$box = $("#attrs .eventItemBox ."+tagName+"Box");
						$(this).children().each(function(){
							var action_id = $(this).attr("action_id"),
								actionType = $(this).find("actionType").html(),
								value = $(this).find("value").html(),
								actionObj = $(ctrlActionsHtml[actionType] || actionHTML[actionType]).attr({action_type : actionType,action_id :  action_id});
								
							
							$box.append(actionObj);
							actions[actionType](ctrl,actionObj,value);
						});
					});
				},

				loadAction = function(ctrl){
					if(ctrl.length <=0){
						return ;
					}
					var ctrlType = ctrl.attr("ctrl-type") ||　"DEFAULT",getCtrl = controlList[ctrlType]().getCtrl(),actions = getCtrl.actions,ctrlActionsHtml = getCtrl['actionHTML'] || {} ,actionStr = [],options = ['<option value="ChooseAction">ChooseAction</option>'];
					for(var key in actions){
						options.push('<option value="'+key+'">'+key+'</option>');
					} 
					$(".actionList").html(options.join(""));
					restoreAction(ctrl);
					$(".actionList").off("change").on("change",function(){
						var key = $(this).val();
						if(key != "ChooseAction"){
							var action_id = uniqueID(++actionIndex), actionObj = $(ctrlActionsHtml[key] || actionHTML[key]).attr({
								action_type : key,
								action_id :  action_id
							}),ctrlId = getCtrId(ctrl);
							$("#attrs .itemBoxContent."+eventType+"Box").append(actionObj);
							actions[key](ctrl,actionObj);
							if($actionXML.find("#"+ctrlId).length<=0){
								$actionXML.append(createActionCtrlXML(ctrlId));	
								ctrlActionXML = $actionXML.find("#"+ctrlId);
							}
							$actionXML.find("#"+ctrlId + " "+eventType).append(createActionItemXML(action_id,key));
							setTimeout(function(){
								$(".actionList option[value='ChooseAction']").prop("selected",true);
							},1000);
						}

					});

					

				},

				createActionCtrlXML = function(id){
					return '<ctrl id="'+id+'"> <Click></Click> <DblClick></DblClick> <MouseDown></MouseDown> <MouseUp></MouseUp> <MouseMove></MouseMove> <MouseOver></MouseOver> <MouseOut></MouseOut> </ctrl>'
				},

				createActionItemXML = function(action_id,actionType){
					return '<item action_id="'+action_id+'"><actionType>'+actionType+'</actionType> <target></target></item>';
				}

				removeAction = function(){
					$("#attrs").on("click",".actionClose",function(){
						ctrlActionXML.find(eventType +" [action_id='"+$(this).closest(".setAction").attr("action_id")+"']")
						$(this).closest(".setAction ").remove();
					});
				},

				uniqueID = function(pre){
					return [new Date().getTime(),pre].join("_");
				},

				selectedCtrl = function(ctrl){
					
					if(ctrl.find(">.lineBox").length<=0 && !ctrl.hasClass("page")){
						ctrl.append('<div class="lineBox"> <div class="circle circle-rotate" data-type="circle-rotate"></div><div class="line rotate-line"></div><div class="line line-n"> <div class="circle" data-type="circle-n"></div> </div> <div class="line line-e"> <div class="circle" data-type="circle-e"></div> </div> <div class="line line-s"> <div class="circle" data-type="circle-s"></div> </div> <div class="line line-w"> <div class="circle" data-type="circle-w"></div> </div> <div class="circle cricle-nw"></div> <div class="circle cricle-ne" data-type="circle-ne"></div> <div class="circle cricle-sw" data-type="circle-sw"></div> <div class="circle cricle-se" data-type="circle-se"></div> </div>');
					}

					if($.inArray(17,ctrlKey) !=-1){
						if(ctrl.hasClass('ctrlSelected')){
							ctrl.removeClass("ctrlSelected");
						}else{
							ctrl.addClass('ctrlSelected');
						}
						loadAttr($(".ctrlSelected"));
					}else{
						if(ctrl.hasClass('ctrlSelected')){return true}

						$(".ctrlSelected").removeClass("ctrlSelected");
						ctrl.addClass("ctrlSelected");
						loadAttr(ctrl);
						loadAction(ctrl);

					}

					$("#attrs").show();
				},

				addCtrlId = function(ctrl){
					var ctrlId = ctrl.attr("data-ctrlId");
					if(!ctrlId){
						var t = new Date().getTime();
						ctrlId = "defindStyle"+t;
						ctrl.attr("data-ctrlId",ctrlId);
					}

					return ctrlId;
				},
				addCtrl = function(item,type,config,data){
					var ctrlType = item.attr("data-type"),ctrl = item,ctrlId = uniqueID(++ctrlIndex),ctrlSelected=$(".ctrlSelected");
					if(ctrlType){
						var getCtrl = controlList[ctrlType]()["getCtrl"]();	

						if(item.hasClass('ctrlItem')){
							ctrl = $(getCtrl['html']);
							ctrl.find(".ctrlTitle").html(getCtrl['title']+ctrlIndex);
							controlList[ctrlType]()["init"](ctrl,config,data);
						}else{
							ctrl = controlList[ctrlType]()["init"](ctrl,config,data);
						}

						if(type == "click"){
							if(ctrlSelected.attr("ctrl-type") == "BOX"){
								ctrlSelected.find(".ctrlBox:first").append(ctrl);
							}else if(ctrlSelected.hasClass("page-struckItem")){
								ctrlSelected.append(ctrl);
							}else if(ctrlSelected.length>0 && ctrlSelected.attr("ctrl-type") != "PAGE" ){
								ctrlSelected.after(ctrl);
							}else{
								$(".xbyl-page-content").append(ctrl);
							}
						}else{
							item.replaceWith(ctrl);
						}

						ctrl.attr("data-ctrlId",ctrlId);
						ctrlList[ctrlId] = {
								ctrlId : ctrlId,
								ctrlType : ctrlType
							};
					}
					selectedCtrl(ctrl);
					
					
					return ctrl;
				},

				removeCtrl = function(ctrl){
					this.config.delete(ctrl);
					//$("#attrs").empty();
					//loadAttr($(".page"));
				};
				
				window.runActionFunList  = runActionFunList;		
				function startDrag(){
				    $(".phoneMain").on("mousedown.circleandctrl",".circle,.ctrl",function(el){
				    	el = el || window.event;
				    	var $this = $(this),
					    	type = $this.attr("data-type"),
					    	px = el.pageX,
					    	py = el.pageY,
					    	ele = $(this).closest(".ctrl"),
					    	h = ele.height(),
					    	w = ele.width(),
					    	t = parseInt(ele.css("top")),
					    	l = parseInt(ele.css("left")),
					    	th = $(".xbyl-page-top").height(),
					    	bh = $(".xbyl-page-bottom").height(),
					    	ch = $(".xbyl-page-content").height();
				    	el.stopPropagation();
				    	
				    	$(document).on("mousemove.circle",function(e){
				    		e = e || window.event;
				    		var ex = e.pageX,ey = e.pageY,x = ex-px,y=ey-py,eh = h+y,ew = x+w,rem = "",flag = false;
				    		e.stopPropagation();
				    		switch(type){
				    			case "circle-n" : 
				    				eh = py>ey ? h+Math.abs(y) : h-Math.abs(y);
				    				ele.css({
				    					"height":(eh),
				    					"top" :(t+y)
				    				});
				    			break;
				    			case "circle-e" :
				    				ew = px>ex ? w+Math.abs(x) : w-Math.abs(x);
				    				ele.css({"width":shiftPercent(ew,ele),left:shiftPercent(l+x,ele)});
				    			 break;
				    			case "circle-s" :
				    				ele.css("height",(eh));
				    			 break;
				    			case "circle-w" : 
				    				ele.css("width",shiftPercent(ew,ele));
				    			break;
				    			case "circle-nw" : 
				    			break;
				    			case "circle-ne" : 
				    			break;
				    			case "circle-sw" : 
				    			break;
				    			case "circle-se" : 
				    			break;
				    			case "circle-rotate" : 
				    			break;
				    			default :
				    				
				    				if(Math.abs(x)>10 || Math.abs(y)>10){
				    					flag = true;
				    				}

					    			if(flag){
						    			ele.css({
						    				left:shiftPercent(l+x,ele),
						    				top:(t+y)
						    			});
					    			}
				    		}
				    	});

				    	$(document).off("mouseup.circle").on("mouseup.circle",function(){
				    		$(document).off("mousemove.circle");
				    		$(document).off("mouseup.circle");
				    	})
				    	
				    });
				}

				function stopDrag(){
					 $(".phoneMain").off("mousedown.circleandctrl");
				}

				$(".ctrlList li").draggable({
					opacity : 0.8,
					addClasses : false,
					helper : function() {
						var html = this.outerHTML;
						$(".page,.ctrlBox").sortable("enable");
						return $(html).css({
						"width" : "200px",
						"font-size" : "10px",

						})[0].outerHTML;
					},
					connectToSortable : ".page",
					distance : "10"
				});

				
				$("body").on("click",".ctrlList .ctrlItem,.imgPanel",function(){
					addCtrl($(this),"click");
				});

				function UEditiorSortable(obj,sortStopCallback,connectWith,placeholder){
					connectWith = ".left li,.page,.ctrlBox"+(connectWith ? ","+connectWith : "");
					placeholder = placeholder ? placeholder : "ctrl-placeholde";
					obj.sortable({
						handel:".ctrlHandel",
						connectWith : connectWith,
						placeholder :placeholder,
						tolerance : 'touch',
						tolerance : 'pointer',
						appendTo : "parent",
						cursor : "move",
						start : function(e, ui) {
							
						},
						stop : function(ev, ui) {
								var ctrl = addCtrl(ui.item);
								$(".page,.ctrlBox").sortable("disable");
								sortStopCallback ? sortStopCallback(ctrl) : (function(ctrl){})(ctrl);
						},

						over : function(ev, ui) {
							
							
						},

						out : function() {
							
						}
					});
				}

				UEditiorSortable($(".page,.ctrlBox"));
				$(".ctrl").draggable();
				$(".page,.ctrlBox").sortable("disable");

				$("body").off("mouseenter.ctrlHandel").on("mouseenter.ctrlHandel",".ctrlHandel,.fileddiv",function(){
					
					$(".page,.ctrlBox").sortable("enable");
				}).off("mouseleave.ctrlHandel").on("mouseleave.ctrlHandel",".ctrlHandel,.fileddiv",function(){
					$(".page,.ctrlBox").sortable("disable");
				});

				window.keyupTime = 0;
				document.onkeydown = function(e){
				  	var event = e ||　window.event,k = event.keyCode;
				  	if($(".ctrlSelected").hasClass("page-struckItem"))return;

				  	if($.inArray(k, ctrlKey) == -1){
				  		ctrlKey.push(k);
				  	}
				  	clearInterval(window.keyupTime);
				  	if(k == 37 ||k == 38 ||k == 39 ||k == 40){
				  		trimPosition(k);
					  	window.keyupTime = setInterval("trimPosition("+k+")",1000);
				    }
				}

				function trimPosition(k){
					let $selectedCtrl = $(".ctrlSelected"),key,value,step=1;
						 		switch(k){
						 			case 37 : 
						 				key = "left";
						 				value = -step;
						 			break;
						 			case 38 :
						 				key = "top";
						 				value = -step;
						 			break;
						 			case 39 :
						 				key = "left";
						 				value = step;
						 			break;
						 			case 40 :
						 				key = "top";
						 				value = step;
						 			break;

						 		}

					 		for(var i=0; i<$selectedCtrl.length;i++){
					 			var itemCtrl = $($selectedCtrl[i]),left = parseInt(itemCtrl.css("left")),top = parseInt(itemCtrl.css("top"));
					 			var v = key=="left" ? (shiftPercent(left+value,$(".ctrlSelected:first"))) : (top+value);
					 			itemCtrl.css(key,v);
					 		}
				}

				document.onkeyup = function(e){
				  	var event = e ||　window.event,k = event.keyCode;
				  	window.keyupTime = clearInterval(window.keyupTime);
				 	
				 	for(var i = 0; i<ctrlKey.length;i++){
				  		if(k == ctrlKey[i]){
				  			ctrlKey.splice(i,1);
				  		}
				 	}
				}


			    $(".center,.page").click(function(event){
			    	if($.inArray(17,ctrlKey) ==-1){
			    		$(".ctrlSelected").removeClass("ctrlSelected");
			    	}
			    });

				$("body").off("click.ctrlSelected").on("click.ctrlSelected",".ctrl",function(e){
					if($(".page").hasClass("settingAction")){
						return;
					}
					e = getEvent(e);
					selectedCtrl($(this));
					e.stopPropagation();
					e.preventDefault();
				});

				

			    $("body").on("contextmenu",".ctrl",function(e){
			    	var event = getEvent(e),pageX = event.pageX-10,pageY = event.pageY-10;
			    	if($(this).hasClass("page-struckItem"))return;
			    	$(".xbyl-RightMenuBox").css({"left":pageX,"top":pageY,"display":"block"});
			    });

			    $(".xbyl-RightMenuBox").mouseout(function(e){
			    	var g = 10,$t=$(this),
				    	rect=this.getBoundingClientRect(),
				    	l = rect.left,
				    	top=rect.top,
				    	w=$t.width(),h=$t.find(".rightMenu").height();
			    	$(document).on("mousemove.RightMenuBox",function(e){
				    	var event = getEvent(e),x=event.pageX,y=event.pageY;
				    	
				    	if(x<l-g || x> (l+w+g) || y<top-g || y>top+h+g){
				    		$(document).off("mousemove.RightMenuBox");
				    		$t.hide(250);
				    	}
			    		
			    	});
			    });

				$("#delete").click(function(){
					$(".xbyl-RightMenuBox").hide();
					$(".setComponent").hide();
					removeCtrl($(".ctrlSelected"));
				});


				function save(){
					$(".ctrlSelected").removeClass('ctrlSelected');
					var clone = $(".page").clone(),style = $("#autoDifinedStyle").length>0?$("#autoDifinedStyle").html():"";
					clone.find(".lineBox").remove();
					clone.find("[ctrl-type='LIST']").each(function(k,v){
						$(v).find(".dataItem").each(function(a,b){
							var field = "{"+$(b).attr("data-field")+"}",
							fiedText = $(b).find(".filedText");
							if(fiedText.hasClass("img")){
								fiedText.attr("src",field);
							}else{
								fiedText.html(field);
							}
						});
					});
					config.save({
						ctrlList : ctrlList,
						template :clone[0].outerHTML,
						style : style,
						userId:"1",
						projectId:"2",
						pageId : clone.attr("id"),
						pagePath:clone.attr("data-path")
					});
				}
				function editroEvent(){

				}

				$("#save").unbind('click').click(function(){
					save();
					
				});

				$("#preview").unbind("click").click(function(){
					save();
					config.preview();
				});

				removeAction();


				$(".addcufa span").click(function(){
					$(this).parent().hide();
					$(".cufaCondition").show();
				});

				$(".eventBox li").click(function(){
					var f = $(this).attr("for");
					eventType = f.replace(".","").replace("Box","");
					$(".cufaCondition").hide();
					$(".itemBoxContent").hide();
					$(f).show();
					$(".addcufa,.action").show()
				});


			

				loadAttr($(".page"));
				$(".xbyl-page-set").click(function(){
					selectedCtrl($(".page"));
				});
				$(".attrItem").click(function(){
					$(".attrBg,.bottomborder").css("left",(50*$(this).index())+"%");
					$(".attrItemBox").hide();
					$("."+$(this).attr("for")).show();
				});

				$(".styleItem").click(function(){
					$(".selectStyleItem").removeClass("selectStyleItem");
					$(this).addClass("selectStyleItem");
					$(".styleBg").css("left",(25*$(this).index())+"%");
					styleType = $(this).attr("type");
				});

				$(".arrow").click(function(){
					var value = parseInt($(".eventList").attr("translate"));
					value = $(this).hasClass("leftArrow") ? (value-120) : (value+120);
					var translate = "translate("+value+"px)";
					 $(".eventList").attr("translate",value);
					setTransform($(".eventList"),translate);
					if(value <=-480 || value >=0){
						setTimeout(function(){
						value = value >=0 ? 5:-480;
						var translate = "translate("+value+"px)";
						$(".eventList").attr("translate",value);
						setTransform($(".eventList"),translate);
						},500);
					}

				});
				
				$(".eventItem").click(function(){
					$(".fictitiousBg").css("left",($(this).index()*120)+"px");
				});	

				$(".page").on("click","[ctrl-type='LIST'].ctrlSelected [ctrl-type='LISTITEM']",function(e){
					getEvent(e).stopPropagation();
					//selectedCtrl($(this));
					$(".selectedDataItem").removeClass("selectedDataItem");
					$(this).addClass("selectedDataItem");
					loadAttr($(this));
					loadAction($(this));
				});

				$(".page").on("mousedown.LISTITEM","[ctrl-type='LIST'].ctrlSelected [ctrl-type='LISTITEM']",function(e){
					getEvent(e).stopPropagation();
					
					$(".dataBox").sortable({
						start : function(){
							stopDrag();
						},
						stop: function(){
							startDrag();
						}
					});
				});
				
				
				startDrag();
			});
			
			return {
				UEditiorSortable : function(obj,sortStopCallback,connectWith,placeholder){
					 UEditiorSortable(obj,sortStopCallback,connectWith,placeholder);
				},

				addCtrl : function(item,type,config,data){
					addCtrl(item,type,config,data);
				},

				ctrlList : ctrlList
			} 
		}


		

	});

});



 